package com.iut.controls;

import java.util.List;

import com.iut.utils.CameraHelper;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback
{
	private Camera camera;
	
	private SurfaceHolder holder;
	
	public CameraPreview(Context context) {
		super(context);
	}
	
	public CameraPreview(Context context, Camera camera) 
	{
		super(context);

		this.camera = camera;
		
		holder = getHolder();
		holder.addCallback(this);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) 
	{
		Log.d("PARCEL_TAG", "SURFACE_CHANGED");
		
		if(holder.getSurface() == null)
			return;
		
		try
		{
			camera.stopPreview();
		}catch(Exception e){ }
		
		if(camera != null)
		{
			Camera.Parameters camParams = camera.getParameters();
			
			List<Size> sizes = camParams.getSupportedPreviewSizes();
				
			Size optimalSize = CameraHelper.getOptimalPreviewSize(sizes, getWidth(), getHeight());
				
			camParams.setPreviewSize(optimalSize.width, optimalSize.height);
			
			camera.setParameters(camParams);
		}
		
		try
		{
			camera.setPreviewDisplay(holder);
			
			camera.startPreview();
		}catch(Exception e){ }
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		Log.d("PARCEL_TAG", "SURFACE_DESTROYED");
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
	}

}
